package com.whynot.frame.auth.jwt.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.whynot.frame.auth.jwt.utils.JWTUtil;
import com.whynot.frame.auth.shiro.cache.AuthCache;
import com.whynot.frame.basic.util.SpringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.web.subject.WebSubject.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Map;

/**
 * 描述: 设置当前用户的信息的拦截器
 * 注意：暂时不使用
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: banke-boot-basic
 * 版本: 1.0.0
 * JDK: since 1.8
 */
//@Deprecated
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String tokenHeader = request.getHeader("Authorization");//从头部获取JWT字符串信息

        if(StringUtils.isNotBlank(tokenHeader)) {
            String userName = JWTUtil.getUsername(tokenHeader);//解码JWT，获得userid
            if(userName!=null) {

                Map<String,Object> user = SpringUtil.getBean(AuthCache.class).getUser(userName);//根据userID获取用户信息
                if(user!=null) {
                    request.setAttribute("currentUser",user);
                    request.setAttribute("userName",userName);
                    /*PrincipalCollection principals = new SimplePrincipalCollection(user, "my_realm2");//拼装shiro用户信息
                    Builder builder = new WebSubject.Builder(request, response);
                    builder.principals(principals);
                    builder.authenticated(true);
                    WebSubject subject = builder.buildWebSubject();
                    ThreadContext.bind(subject);*///塞入容器，统一调用
                }

            }
        }
        chain.doFilter(request, response);
    }

}
